<template>
  <a-modal
    title="编辑用户表"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item v-show="false"><a-input v-decorator="['id']" /></a-form-item>
        <a-form-item
          label="登录名"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-input disabled="disabled" placeholder="请输入登录名称 即为：手机号"  v-decorator="['loginName', {rules: [{required: true, message: '请输入登录名称 即为：手机号！'}]}]" />
        </a-form-item>
<!--        <a-form-item-->
<!--          label="头像"-->
<!--          :labelCol="labelCol"-->
<!--          :wrapperCol="wrapperCol"-->
<!--          has-feedback-->
<!--        >-->
<!--          <a-upload-->
<!--            :customRequest="customRequest"-->
<!--            :multiple="false"-->
<!--            :showUploadList="false"-->
<!--          >-->
<!--            <a-button>-->
<!--              <a-icon type="upload"/>-->
<!--              <span v-if="headPicId > 0">重新上传</span>-->
<!--              <span v-else>上传头像</span>-->
<!--            </a-button>-->
<!--              <img v-if="headPicId > 0" :src="headPicUrl" style="width:150px">-->
<!--          </a-upload>-->
<!--        </a-form-item>-->

        <a-form-item
          label="头像"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-upload
            :customRequest="customRequest"
            :multiple="true"
            :showUploadList="false"
            :remove="removeImg"
          >
            <a-button>
              <a-icon type="upload"/>
              点击上传
            </a-button>
          </a-upload>
            <img :src="headPicUrl" style="width:150px">
        </a-form-item>

        <a-form-item
          label="昵称"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-input placeholder="请输入昵称" v-decorator="['nick', {rules: [{required: true, message: '请输入昵称！'}]}]" />
        </a-form-item>
        <a-form-item
          label="性别"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-select style="width: 100%" placeholder="请选择性别" v-decorator="['sex', {rules: [{ required: true, message: '请选择性别！' }]}]" >
            <a-select-option v-for="(item,index) in userSexDict" :key="index" :value="item.code" >{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="生日"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-date-picker style="width: 100%" placeholder="请选择生日" v-decorator="['birthday',{rules: [{ required: false, message: '请选择生日！' }]}]" @change="birthdayOnChange"/>
        </a-form-item>
        <a-form-item
          label="详细地址"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-input placeholder="请输入详细地址" v-decorator="['address', {rules: [{required: false, message: '请输入详细地址！'}]}]" />
        </a-form-item>
        <a-form-item
          label="签名"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-input placeholder="请输入签名" v-decorator="['sign', {rules: [{required: false, message: '请输入签名！'}]}]" />
        </a-form-item>
        <a-form-item
          label="账号状态"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-select style="width: 100%" disabled="" placeholder="请选择账号状态" v-decorator="['status', {rules: [{ required: true, message: '请选择账号状态' }]}]" >
            <a-select-option v-for="(item,index) in userAccountStatusDict" :key="index" :value="item.code" >{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="会员状态"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-select  style="width: 100%" placeholder="请选择会员状态" v-decorator="['vip', {rules: [{ required: true, message: '请选择会员状态！' }]}]" >
            <a-select-option v-for="(item,index) in vipStatusDict" :key="index" :value="item.code" >{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="门票状态"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-select  style="width: 100%" placeholder="请选择门票状态" v-decorator="['ticket', {rules: [{ required: true, message: '请选择会员状态！' }]}]" >
            <a-select-option v-for="(item,index) in ticketStatusDict" :key="index" :value="item.code" >{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="在线状态"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-select  style="width: 100%" placeholder="请选择在线状态" v-decorator="['onlineStatus', {rules: [{ required: true, message: '请选择在线状态！' }]}]" >
            <a-select-option v-for="(item,index) in userOnlineStatusDict" :key="index" :value="item.code" >{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="注册时间"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-date-picker style="width: 100%" disabled="" placeholder="请选择注册时间" v-decorator="['createTime',{rules: [{ required: true, message: '请选择注册时间！' }]}]" @change="createTimeOnChange"/>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import moment from 'moment'
  import { appUserEdit } from '@/api/modular/app/user/appUserManage'
  import { sysFileInfoUploadFront } from '@/api/modular/system/fileManage'
  export default {
    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        birthdayDateString: '',
        createTimeDateString: '',
        visible: false,
        confirmLoading: false,
        form: this.$form.createForm(this),
        // 用户性别
        userSexDict: [],
        // 用户账号状态
        userAccountStatusDict: [],
        // 用户会员状态
        vipStatusDict: [],
        // 门票状态
        ticketStatusDict: [],
        // 用户在线状态
        userOnlineStatusDict: [],
        fileBucket: 'userinfo', // 第一层级桶名
        userId: '', // 用户id
        // 头像赋值
        oldHeadPicId: '', // 旧头像id
        headPicId: '', // 头像id
        headPicUrl: '', // 头像url
        fileList: [],
        previewVisible: false,
        previewImage: '',
        maxMagNum: 999
      }
    },
    created () {
      // 初始化字典下来
      this.sysDictTypeDropDown()
    },
    methods: {
      moment,
      // 初始化方法
      edit (record) {
        this.visible = true
        this.userId = record.id // 赋值用户id
        this.oldHeadPicId = record.headPicId // 赋值用户旧的头像id
        this.headPicId = record.headPicId // 赋值用户新头像id
        this.headPicUrl = record.headPicUrl // 赋值用户的头像url
        setTimeout(() => {
          this.form.setFieldsValue(
            {
              id: record.id,
              loginName: record.loginName,
              nick: record.nick,
              sex: record.sex.toString(),
              sign: record.sign,
              status: record.status.toString(),
              loginNum: record.loginNum,
              lastLoginIp: record.lastLoginIp,
              vip: record.vip.toString(),
              ticket: record.ticket.toString(),
              address: record.address,
              onlineStatus: record.onlineStatus.toString()
            }
          )
        }, 100)
        // 时间单独处理
        if (record.birthday) {
          this.form.getFieldDecorator('birthday', { initialValue: moment(record.birthday, 'YYYY-MM-DD') })
          this.birthdayDateString = moment(record.birthday).format('YYYY-MM-DD')
        }
        // 注册时间
        if (record.createTime) {
          this.form.getFieldDecorator('createTime', { initialValue: moment(record.createTime, 'YYYY-MM-DD') })
          this.createTimeDateString = moment(record.createTime).format('YYYY-MM-DD')
        }
      },
      /**
       * 获取字典数据
       */
      sysDictTypeDropDown () {
        this.userSexDict = this.$options.filters['dictData']('user_sex')
        this.userAccountStatusDict = this.$options.filters['dictData']('user_account_status')
        this.vipStatusDict = this.$options.filters['dictData']('vip_status')
        this.ticketStatusDict = this.$options.filters['dictData']('ticket_status')
        this.userOnlineStatusDict = this.$options.filters['dictData']('user_online_status')
      },
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            // 判断是否有上传新头像 有赋值
            if (this.headPicId !== this.oldHeadPicId) {
              values.headPicId = this.headPicId
            }
            appUserEdit(values).then((res) => {
              if (res.success) {
                // 删除旧的头像  废弃 后端处理
                // if (this.oldHeadPicId > 0 && this.headPicId !== this.oldHeadPicId) {
                //   sysFileInfoDelete({ id: this.oldHeadPicId })
                // }
                this.$message.success('编辑成功')
                this.confirmLoading = false
                this.$emit('ok', values)
                this.handleCancel()
              } else {
                this.$message.error('编辑失败')//  + res.message
              }
            }).finally((res) => {
              this.confirmLoading = false
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      birthdayOnChange(date, dateString) {
        this.birthdayDateString = dateString
      },
      createTimeOnChange(date, dateString) {
        this.createTimeDateString = dateString
      },
      handleCancel () {
        this.birthdayDateString = ''
        this.form.getFieldDecorator('birthday', { initialValue: null })
        this.createTimeDateString = ''
        this.form.getFieldDecorator('createTime', { initialValue: null })
        this.form.resetFields()
        this.visible = false
      },
      /**
       * 上传文件
       */
      customRequest (data) {
        const formData = new FormData()
        formData.append('file', data.file)
        formData.append('fileBucket', this.fileBucket)
        formData.append('userId', this.userId)
        sysFileInfoUploadFront(formData).then((res) => {
          if (res.success) {
            // 赋值到headPicId headPicUrl字段
            this.headPicId = res.data.filedId
            this.headPicUrl = res.data.sysFileInfo
            this.$message.success('上传成功')
          } else {
            this.$message.error('上传失败：' + res.message)
          }
        })
      },
      /**
       * 删除图片方法
       *
       * @param data
       */
      removeImg(data) {
          this.fileList = this.fileList.filter(item => item.uid !== data.uid)
      }

    }
  }
</script>
